/*    Copyright 2010 Tobias Marschall
 *
 *    This file is part of MoSDi.
 *
 *    MoSDi is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    MoSDi is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with MoSDi.  If not, see <http://www.gnu.org/licenses/>.
 */

package mosdi.tests;

import junit.framework.TestCase;
import mosdi.util.Bits;

public class BitsTest extends TestCase {

	private void assertElias(long x) {
		Bits.ValueAndBitLength vb = Bits.eliasEncode(x);
		assertTrue(vb.bits<=64);
		for (int i=0; vb.bits+i<=64; ++i) {
			Bits.ValueAndBitLength vbDec = Bits.eliasDecode(vb.value<<i, vb.bits-1+i); 
			assertEquals(x, vbDec.value);
			assertEquals(vb.bits, vbDec.bits);
			vbDec = Bits.eliasDecode((vb.value<<i) | ((1<<i)-1), vb.bits-1+i); 
			assertEquals(x, vbDec.value);
			assertEquals(vb.bits, vbDec.bits);
		}
		for (int i=1; i<vb.bits; ++i) {
			try {
				Bits.eliasDecode(vb.value>>>i, vb.bits-1-i);
				fail("Exception expected!");
			} catch (IllegalArgumentException e) {}
		}
	}
	
	public void testElias() {
		long[] numbers = {0, 1, 2, -1, -2, (1L<<51)-1, -(1L<<50)+1, -31884L, -22691L, 29537L, -20333L, -2573L, 23277L, -24446L, -1097L, -13346L, 31436L, 17743L, -6701L, -21915L, 20889L, 31610L, 287817132L, 179734999L, 2119069339L, 1848230359L, -1446670964L, 1202929276L, -944218106L, -1007393965L, -731895518L, 1131166369L, 1425558909L, 14014756L, -364595802L, -451879437L, 1826895576L, 2103680141703292L, -134421522259323L, 1900045508938986L, 1062130732404855L, -880190823983923L, -624718369750848L, -125244196039690L, 705597856559575L, 1863533500195618L, 1850256882678956L, -142078830642925L, 1393722226077487L, -50622990219973L, 1103911671450321L, -732236430151173L, -155799071809838L, 2145432957168621L, 1098212251019327L, -1093746830519094L, -584943629627595L, -1097376853758552L, 1547430982320086L, -1052616847705351L, 379724923114538L, -437915725884321L}; 
		for (long l : numbers) assertElias(l);
	}
	
}
